package com.gitee.lougnib.simple.mybatis.generator.plugin;

import java.util.List;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

/**
 * 在 Entity 的 set 方法中，加入删除右侧半角空格和全角空格的处理。
 *
 * @author lougnib@163.com
 * @since 2021/07/16
 * @version 2021/07/16
 */
public class EntityTrimRightPlugin extends PluginAdapter {

	@Override
	public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass,
			IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {

		if (method.getName().startsWith("set")
				&& method.getParameters().get(0).getType().equals(FullyQualifiedJavaType.getStringInstance())) {
			List<String> list = method.getBodyLines();
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					String item = list.get(i);
					list.set(i, item.replace(";", "") + " == null ? null : StringUtils.stripEnd("
							+ introspectedColumn.getJavaProperty() + ", \" 　\");");
				}

				topLevelClass.addImportedType("org.apache.commons.lang3.StringUtils");
			}
		}

		return true;
	}

	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}
}
